package com.sunchangming.stmdb;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class MyThread extends Thread {
	private boolean idle = true;
	private volatile boolean running = true;
	private final Runnable task;
	private final long period;
	private final static Logger logger = LoggerFactory.getLogger(MyThread.class);
	private final ReentrantLock lock = new ReentrantLock();
	private final Condition cond = lock.newCondition();

	public final boolean isRunning() {
		return running;
	}

	public void shutdown() {
		running = false;
		wakeup();
		joinAssuring();
	}

	/**
	 * 忽略中断异常，必须等待线程结束。
	 */
	public final void joinAssuring() {
		while (true) {
			try {
				join();
				break;
			} catch (final Throwable ex) {
				logger.warn("shutdown. ignore ex=", ex);
			}
		}
	}

	public synchronized void wakeup() {
		lock.lock();
		try {
			idle = false;
			cond.signalAll();
		} finally {
			lock.unlock();
		}
	}

	/**
	 * 
	 * @param name
	 *            线程名
	 * @param task
	 *            要执行的任务
	 * @param period
	 *            执行间隔，单位千分之一秒
	 */
	MyThread(String name, Runnable task, long period) {
		super(name);
		this.task = task;
		this.period = period;
	}

	@Override
	public void run() {
		while (isRunning()) {
			try {
				task.run();
				sleepIdle(period);
			} catch (final Throwable ex) {
				logger.error("angel run " + ex);
			}
		}
	}

	public final void sleepIdle(long ms) {
		lock.lock();
		try {
			if (idle)
				cond.await(ms, TimeUnit.MILLISECONDS);
		} catch (final InterruptedException ex) {
			logger.warn("sleepOut. ex=", ex);
		} finally {
			idle = true;
			lock.unlock();
		}
	}

}
